<template>
  <div class="step4">
    <!-- 上传PDF -->
    <div style="float:left;">
      <UploadFile
        ref="upDateUploadFile"
        :FileUrl="fileUploadUrl"
        :isMultiple="false"
        :isAutoUpload="true"
        :Data="Data"
        :fileType="fileType"
        :beforeAvatarUpload="beforeAvatarUpload"
        :handleAvatarSuccess="handleAvatarSuccess"
      ></UploadFile>
    </div>
    <el-button style=" float: left; margin-left: -390px;" @click="toExcel" size="small" type="primary">生成Excel</el-button>

    <!-- 最新上传记录 -->
    <el-table :data="recordList" stripe highlight-current-row>
      <el-table-column type="index" min-width="100"></el-table-column>
      <el-table-column prop="originname" label="文件名"></el-table-column>
      <el-table-column prop="createdAt" label="上传时间"></el-table-column>
      <el-table-column fixed="right" label="操作" width="130">
        <template slot-scope="scope">
          <el-button @click="fileDownload(scope.row)" icon="el-icon-download" size="small" type="primary"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="dataInfo" v-if="recordList.length>0">
      <div class="tit">数据信息</div>
      <el-button-group>
        <el-button v-if="projectType==2" @click="handleSetLineChartData('total','1')">总图</el-button>
        <el-button v-if="projectType==3" @click="handleSetLineChartData('yuleng','1')">预冷</el-button>
        <el-button v-for="item in kaiguanmencount" :key="item" @click="handleSetLineChartData('kaiguanmen','item')">第{{item}}次开关门</el-button>
        <el-button v-if="projectType==3" @click="handleSetLineChartData('baowen','1')">保温</el-button>
        <el-button v-if="projectType==3" @click="handleSetLineChartData('wentai','1')">稳态</el-button>
      </el-button-group>

      <line-chart :chartData="lineChartData" v-loading="listLoading" v-show="isShow" />
    </div>

    <el-card style="margin-top:20px;">
      <div slot="header" class="clearfix">
        <span>历史上传记录</span>
      </div>
      <el-table :data="historyList" stripe highlight-current-row>
        <el-table-column type="index" min-width="100"></el-table-column>
        <el-table-column prop="originname" label="文件名"></el-table-column>
        <el-table-column prop="createdAt" label="上传时间"></el-table-column>
        <el-table-column fixed="right" label="操作" width="130">
          <template slot-scope="scope">
            <el-button @click="fileDownload(scope.row)" icon="el-icon-download" size="small" type="primary"></el-button>
            <el-button
              v-if="checkPermission(['manager'])"
              @click.native.prevent="handleDel(scope.$index, scope.row)"
              icon="el-icon-delete"
              size="small"
              type="danger"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
import countTo from "vue-count-to";
import { parseTime } from "@/utils";
import LineChart from "@/components/Echart/LineChart";
import checkPermission from "@/utils/permission"; // 权限判断函数
import {
  getRecordList,
  deleteRecord,
  getRecordData,
  getRecordGroupData,
  getRecordGroupCount
} from "@/api/record";
import UploadFile from "@/components/Upload/UploadFile2";
import { getProjectData, updateProjectState } from "@/api/project";
const lineChartData = {
  total: {
    timeArray: [],
    sensorCodeArray: [],
    temperArray: []
  },
  yuleng: {
    timeArray: [],
    sensorCodeArray: [],
    temperArray: []
  },
  kaiguanmen: {
    timeArray: [],
    sensorCodeArray: [],
    temperArray: []
  },
  baowen: {
    timeArray: [],
    sensorCodeArray: [],
    temperArray: []
  },
  wentai: {
    timeArray: [],
    sensorCodeArray: [],
    temperArray: []
  }
};
export default {
  name: "Step4",
  components: { UploadFile, LineChart },
  props: ["getId"],
  data() {
    return {
      fileType:
        "txt或csv，上传文件需要删除“Datarecordid”，修改时间格式和“UTF-8”编码",
      recordList: [],
      historyList: [],
      listLoading: false,
      fileUploadUrl: "http://gsp.coldcloud.com/record/upload",
      Data: {},
      projectType: 1,
      kaiguanmencount: null,
      isShow: false,
      lineChartData: lineChartData.total
    };
  },
  created() {
    this.getList();

    //this.getData(0);
  },
  methods: {
    checkPermission,
    // 上传前文件校验
    beforeAvatarUpload(file) {
      const isTXT =
        file.type == "text/plain" || file.type == "application/vnd.ms-excel";
      const isLt5M = file.size / 1024 / 1024 < 100;
      if (!isTXT) {
        this.$message.error("上传文件只能是txt或csv格式!");
      }
      if (!isLt5M) {
        this.$message.error("上传文件大小不能超过100MB!");
      }
      return isTXT && isLt5M;
    },

    // pdf上传成功后
    handleAvatarSuccess(response, file, fileList) {
      this.$message({
        message: "原始数据上传成功",
        type: "success"
      });
      this.getList();
      updateProjectState({ pid: this.getId, state: 4 }).then(_ => {
        this.$emit("changeState");
      });
    },

    // 根据type类型获取对应数据
    handleSetLineChartData(verifyType, verifyCounter) {
      this.isShow = true;
      switch (verifyType) {
        case "total":
          this.getData(0, verifyCounter);
          break;
        case "yuleng":
          this.getData(1, verifyCounter);
          break;
        case "kaiguanmen":
          this.getData(2, verifyCounter);
          break;
        case "baowen":
          this.getData(3, verifyCounter);
          break;
        default:
          this.getData(4, verifyCounter);
      }
      this.lineChartData = lineChartData[verifyType];
    },

    //生成Excel
    toExcel() {},

    //获取列表
    getList() {
      this.listLoading = true;
      // 文件上传时附带的额外参数
      this.Data = { projectId: this.getId };
      // 获取项目类型
      getProjectData({ projectId: this.getId }).then(res => {
        this.projectType = res.data.projectType;
      });
      //获取上传文件和历史上传记录
      getRecordList({ projectId: this.getId }).then(response => {
        this.historyList = response.data.slice(1);
        this.recordList = response.data.slice(0, 1);
        if (this.recordList.length > 0) {
          this.getGroupCount();
        }
        this.listLoading = false;
      });
    },
    //根据项目ID和验证过程类型获取该项目原始数据的阶段分类
    getGroupCount() {
      getRecordGroupCount({ projectId: this.getId })
        .then(res => {
          res.data.forEach(item => {
            if (item.verifyType == 2) {
              this.kaiguanmencount = item.verifyCounter;
            }
          });
        })
        .catch(e => console.log("getRecordGroupCount" + e));
    },

    //获取数据信息
    getData(verifyType, verifyCounter) {
      this.listLoading = true;
      //总图：5  预冷：1，开关门:2，保温:3，稳态:4
      getRecordGroupData({
        projectId: this.getId,
        verifyType: verifyType,
        verifyCounter: verifyCounter
      })
        .then(response => {
          let dataObject = { timeSet: new Set() };
          // 获取探头号
          response.data.map((c, index) => {
            dataObject.timeSet.add(parseTime(c.operDate, "{m}-{d} {h}:{i}"));
            if (dataObject[c.sensorCode] == null) {
              dataObject[c.sensorCode] = [];
            }
            dataObject[c.sensorCode].push(c.temperature);
          });
          // 清空lineChartData里的数据
          this.lineChartData.sensorCodeArray = [];
          this.lineChartData.temperArray = [];
          Object.keys(dataObject).forEach(key => {
            if (Number(key)) {
              this.lineChartData.sensorCodeArray.push(`${key}#`);
              const child = {
                name: `${key}#`,
                data: dataObject[key],
                type: "line",
                smooth: true,
                animationDuration: 2800,
                animationEasing: "cubicInOut"
              };
              this.lineChartData.temperArray.push(child);
            } else {
              this.lineChartData.timeArray = Array.from(dataObject[key]);
            }
          });
          this.listLoading = false;
        })
        .catch(e => {
          this.listLoading = false;
          console.log(e);
        });
    },

    // 下载
    fileDownload(row) {
      window.open(row.url);
    },

    //删除
    handleDel(index, row) {
      this.$confirm("确认删除该文件吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          deleteRecord({ recordLogId: row.id }).then(() => {
            this.listLoading = false;
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.dataInfo {
  margin: 30px 0;
  .tit {
    line-height: 40px;
    border-bottom: 1px solid #ebeef5;
    font-weight: 700;
    margin-bottom: 20px;
  }
}
</style>


